package com.summer.framework.system.controller;

import com.summer.framework.base.exception.SummerRuntimeException;
import com.summer.framework.base.lock.LockService;
import com.summer.framework.base.result.Result;
import com.summer.framework.base.result.ResultUtil;
import com.summer.framework.system.controller.dto.CategoryDTO;
import com.summer.framework.system.controller.dto.CategoryItemSaveDTO;
import com.summer.framework.system.error.SystemError;
import com.summer.framework.system.service.CategoryService;
import com.summer.framework.system.service.CategoryValueService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.Lock;

/**
 * 数据字典
 * @author Ice
 * @since 2025-09-25
 */
@RestController
@RequestMapping("/category")
@RequiredArgsConstructor
public class CategoryController {

    private static final String CATEGORY_CODE_LOCK_KEY = "categoryCodeLockKey";

    private final CategoryService categoryService;

    private final LockService lockService;

    private final CategoryValueService valueService;

    /**
     * 保存
     */
    @PostMapping("/save")
    public Result<String> save(@RequestBody CategoryDTO dto) {
        Lock lock = lockService.getLock(CATEGORY_CODE_LOCK_KEY);
        lock.lock();
        try {
            String code = dto.getCode();
            CategoryDTO old = categoryService.getByCode(code);
            if(old != null){
                throw new SummerRuntimeException(SystemError.CATEGORY_TYPE_EXIST);
            }
            categoryService.saveCategory(dto);
        }finally {
            lock.unlock();
        }
        return ResultUtil.success();
    }

    /**
     * 保存字典项
     */
    @PostMapping("/saveItem")
    public Result<String> saveItem(@RequestBody CategoryItemSaveDTO dto){
        CategoryDTO old = categoryService.getByCode(dto.getCategoryCode());
        if(old == null){
            throw new SummerRuntimeException(SystemError.CATEGORY_TYPE_NOT_EXIST);
        }
        if(dto.getItems() == null || dto.getItems().isEmpty()){
            throw new SummerRuntimeException(SystemError.CATEGORY_TYPE_DETAIL_EMPTY);
        }
        dto.getItems().forEach(item -> item.setType(dto.getCategoryCode()));

        return ResultUtil.success();
    }

}
